<template>
  <div class="role-container">
    <div>
      <!-- 按钮 -->
      <el-button
        size="small"
        type="primary"
        @click="addRole"
      >添加角色</el-button>
    </div>
    <div class="rc-table">
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="name" label="角色" align="center" width="200">
          <template scope="scope">
            <el-input v-if="scope.row.edit" v-model="currentRow.name" />
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" align="center" width="200">
          <template scope="scope">
            <el-switch
              v-if="scope.row.edit"
              v-model="currentRow.state"
              :active-value="1"
              :inactive-value="0"
            />
            <p v-else>{{ scope.row.state ? "已启用" : "未启用" }}</p>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述" align="center">
          <template scope="scope">
            <el-input
              v-if="scope.row.edit"
              v-model="currentRow.description"
              type="textarea"
            />
            <p v-else>{{ scope.row.description }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template scope="scope">
            <div v-if="scope.row.edit">
              <el-button
                type="primary"
                :loading="updateLoading"
                @click="updateRolesTmp(scope.row)"
              >确认</el-button>
              <el-button @click="scope.row.edit = false">取消</el-button>
            </div>
            <div v-else>
              <el-button
                type="text"
                @click="updatePermissions(scope.row)"
              >分配权限</el-button>
              <el-button
                type="text"
                @click="editRole(scope.row)"
              >编辑</el-button>
              <el-popconfirm
                style="margin-left: 10px"
                title="这是一段内容确定删除吗？"
                @onConfirm="delRole(scope.row)"
              >
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="rc-page">
      <!-- 分页 -->
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageParams.pagesize"
        :page-sizes="[5, 10, 15, 20]"
        :current-page="pageParams.page"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增角色弹出框 -->
    <el-dialog
      title="新增角色"
      :visible.sync="dialogVisible"
      width="26%"
      style="padding: 20px 30px"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch
            v-model="ruleForm.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="ruleForm.description" type="textarea" />
        </el-form-item>
        <el-form-item>
          <div style="width: 100%; text-align: center">
            <el-button
              type="primary"
              :loading="addLoading"
              @click="submitForm('ruleForm')"
            >确 定</el-button>
            <el-button @click="resetForm('ruleForm')">取 消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <PermissonTree ref="permissonTree" :visible.sync="treeVisible" />
  </div>
</template>

<script>
import {
  getRolesRequest,
  addRolesRequest,
  updateRolesRequest,
  deleteRolesRequest
} from '@/api/role'
import PermissonTree from './components/permissonTree'
export default {
  name: 'RoleCom',
  components: {
    PermissonTree
  },
  data() {
    const validateName = (_, value, callback) => {
      const arr = this.tableData.filter((item) => item.name === value)
      if (arr.length > 0) {
        return callback(new Error('角色名称已存在'))
      }
      callback()
    }
    return {
      tableData: [],
      pageParams: {
        page: 1,
        pagesize: 5
      },
      total: 0,
      currentRow: null,
      dialogVisible: false,
      treeVisible: false,
      addLoading: false,
      updateLoading: false,
      ruleForm: {
        name: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { validate: validateName, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  /*  async mounted() {
    for (let i = 0; i < 20; i++) {
      this.ruleForm.name = i + '角色名称' + '来继续删'
      this.ruleForm.description = i + '角色描述' + '来继续删'
      await addRolesRequest(this.ruleForm)
    }
  }, */
  methods: {
    addRole() {
      this.dialogVisible = true
    },
    editRole(row) {
      if (this.updateLoading) {
        return
      }
      this.tableData.forEach((item) => {
        item.edit = false
      })
      row.edit = true
      // 如果不提前添加则可以使用$set方法通知视图进行更新0
      // this.$set(row, 'edit', true)
      this.currentRow = JSON.parse(JSON.stringify(row))
    },
    async delRole(row) {
      try {
        if (this.tableData.length === 1) {
          this.pageParams.page === 1
            ? this.pageParams.page
            : this.pageParams.page--
        }
        const res = await deleteRolesRequest(row.id)
        this.$message.success(res.message)
        this.getRoleList()
      } catch (err) {
        //
      }
    },
    async getRoleList() {
      let res = await getRolesRequest(this.pageParams)
      // 需要先将数据进行添加再赋值到vue
      if (res.data.rows.length === 0) {
        this.pageParams.page === 1
          ? this.pageParams.page
          : this.pageParams.page--
      }
      res = await getRolesRequest(this.pageParams)
      res.data.rows.forEach((item) => {
        item.edit = false
      })
      // 在数据添加到vue的时候会直接对数据递归执行将所有数据变为响应式,这时再添加则无法监听到数据的更改,所有应该是先添加再赋值
      // 基于源码为Object.defineProperty(this.tableData, 'rows', { value: res.data.rows })使数据变为响应式
      // 对应源码为defineReactive()
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    handleCurrentChange(page) {
      console.log(page)
      this.pageParams.page = page
      this.getRoleList()
    },
    handleSizeChange(size) {
      this.pageParams.page = 1
      this.pageParams.pagesize = size
      this.getRoleList()
    },
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid && !this.addLoading) {
          try {
            this.addLoading = true
            const res = await addRolesRequest(this.ruleForm)
            this.addLoading = false
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.resetForm(formName)
            await this.getRoleList()
          } catch (err) {
            // this.addLoading = false
          } finally {
            this.addLoading = false
          }
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.dialogVisible = false
    },
    async updateRolesTmp(row) {
      const arr = this.tableData.filter((item) => item.name !== row.name)
      if (arr.some((item) => item.name === row.name)) {
        return this.$message({
          message: '角色名称已存在',
          type: 'error'
        })
      }
      if (!this.currentRow.name || !this.currentRow.description) {
        return this.$message({
          message: '角色名称或描述不能为空',
          type: 'error'
        })
      }
      this.updateLoading = true
      try {
        if (!this.updateLoading) {
          return
        }
        const res = await updateRolesRequest(this.currentRow)
        row.edit = false
        row.name = this.currentRow.name
        row.description = this.currentRow.description
        row.state = this.currentRow.state
        this.$message({
          message: res.message,
          type: 'success'
        })
      } catch (err) {
        // this.updateLoading = false
      } finally {
        this.updateLoading = false
      }
    },
    updatePermissions(row) {
      this.$nextTick(() => {
        this.$refs.permissonTree.getRoleDetail(row.id)
      })
      this.treeVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.role-container {
  padding: 20px;
  .rc-table {
    margin: 20px 0;
  }
  .rc-page {
    text-align: right;
  }
}
</style>
